package com.hqd.ch03.v4.reader;

import com.hqd.ch03.v4.io.Resource;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.List;
import java.util.Map;

/**
 * 解析xml配置
 */
public class XmlBeanDefinitionReader implements BeanDefinitionReader {
    private Map<String, Object> bdMap;

    public XmlBeanDefinitionReader(Map<String, Object> bdMap) {
        this.bdMap = bdMap;
    }

    private void initBean(Object bean, List<Element> properties) {
        try {
            properties.forEach(property -> {
                String name = property.attributeValue("name");
                String value = property.attributeValue("value");
                try {
                    BeanUtils.setProperty(bean, name, value);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private Object createBean(String className) {
        try {
            return Class.forName(className).getConstructor().newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void loadBeanDefinition(Resource resource) {
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(resource.getInputStream());
            Element rootElement = document.getRootElement();
            List<Element> beanEles = rootElement.elements("bean");
            beanEles.forEach(beanEle -> {
                String className = beanEle.attributeValue("class");
                Object bean = createBean(className);
                List<Element> properties = beanEle.elements("property");
                if (CollectionUtils.isNotEmpty(properties)) {
                    initBean(bean, properties);
                }
                bdMap.put(beanEle.attributeValue("id"), bean);
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
